package com.cory.boot.component.uploader;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baidu.ueditor.ActionEnter;
import com.cory.utils.file.FileUtils;

/**
 * 百度UE富文本文件上传
 */
@Slf4j
@Controller
@RequestMapping("/baidu/editor")
public class UEditorUploaderController {

    @RequestMapping(value = "/upload")
    @ResponseBody
    public Map<String, Object> upload(String action, HttpServletRequest request, HttpServletResponse response) {
    //在上传文件后，会返回response，
    //通常会导致客户端（浏览器）不能识别内容编码，
    // 如果客户端(浏览器)采用非UTF-8方式(比如gbk)解码，
    // 客户端就会产生乱码问题。
        response.setContentType("application/json");
        String configPath = "static/plugins/ueditor-plus/lang";
        Map<String, Object> rs = new HashMap<String, Object>();
        MultipartHttpServletRequest mReq = null;
        MultipartFile file = null;
        // 原始文件名   UEDITOR创建页面元素时的alt和title属性
        String originalFileName = "";
        try {
            if ("config".equals(action)) {    //如果是初始化
                String rootPath = ResourceUtils.getURL("classpath:").getPath();
                log.info("rootPath --> " + rootPath);
                response.setCharacterEncoding("UTF-8");

                String exec = new ActionEnter(request, rootPath, configPath).exec();

                PrintWriter writer = response.getWriter();

                writer.write(exec);

                writer.flush();

                writer.close();
            } else if ("uploadimage".equals(action) || "uploadvideo".equals(action) || "uploadfile".equals(action)){
                mReq = (MultipartHttpServletRequest) request;
                // 从config.json中取得上传文件的ID
                file = mReq.getFile("upfile");
                if (file.isEmpty()) {
                    throw new Exception("上传文件不能为空");
                }

                //获取文件后缀
                String fileName = file.getOriginalFilename();
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                String newName = com.cory.utils.lang.DateUtils.getDate("yyyyMMddHHmmss") + "_" + new Random().nextInt(1000) + "." + suffix;

                String fileId = "/resource/ueditor/" + com.cory.utils.lang.DateUtils.getYear() + "/" + com.cory.utils.lang.DateUtils.getMonth() + "/" + newName;
                String fullPath = UploaderConfig.resource + fileId;

                FileUtils.createFile(fullPath);
                FileUtils.copyToFile(file.getInputStream(), new File(fullPath));

                rs.put("state", "SUCCESS");// UEDITOR的规则:不为SUCCESS则显示state的内容
                rs.put("url", UploaderConfig.domain + fileId);         //能访问到你现在图片的路径
                rs.put("title", originalFileName);
                rs.put("original", originalFileName);
                return rs;

            }
        } catch (IOException e) {

            e.printStackTrace();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
